<?php

require_once 'plugin/DBPlugin.php';
require_once 'plugin/Thumbnail.php';

/**
 * Manejo de la seccion Planes
 */
class PlanesDBPlugin extends DBPlugin {


	/**
	 * Obtener un plan por id
	 */	
	public static function getById($id) {

		require_once ('include/connect.php');
		
		$sql = "SELECT * FROM `planes` where idplan = ".$id;
		$result = mysql_query($sql);
		$num = mysql_num_rows($result);
		if ($num > 0) {
			$row = mysql_fetch_array($result);
			return $row;
		}
		return null;
	
	}


	/**
	 * Obtiene los planes
	 */	
	public static function getPlanes($start, $totalPage) {

		require_once ('include/connect.php');
		
		$sql = "SELECT * FROM `planes`".
				" LIMIT ". $start." , ". $totalPage;
		$result = mysql_query($sql);

		return $result;
	
	}
	
	/**
	 * Obtiene la cantidad de planes
	 */	
	public static function getPlanesCount() {

		require_once ('include/connect.php');
		
		$sql = "SELECT count(*) as cant FROM `planes`";
		$result = mysql_query($sql);
		$num = mysql_num_rows($result);
		if ($num > 0) {
			$row = mysql_fetch_array($result);
			return $row[cant];
		}		
		return 0;
	
	}

	
	/**
	 * Publica / no publica un plan
	 */
	public static function publish($id) {

		require_once ('include/connect.php');
		
		$plan = PlanesDBPlugin::getById($id);

		$sql = "";
		if ($plan[published] == 1) {
			$sql = "UPDATE `planes`".
					" SET published=0".
					" WHERE idplan=".$id;
		}
		else {
			$sql = "UPDATE `planes`".
					" SET published=1".
					" WHERE idplan=".$id;		
		}
		
		mysql_query($sql);
	
	}

	
	

	/**
	 * Publica / no publica un content de un plan
	 */
	public static function publishContent($id, $contenttype) {

		require_once ('include/connect.php');
		
		$plan = PlanesDBPlugin::getById($id);

		$sql = "";
		if ($plan[$contenttype."_published"] == 1) {
			$sql = "UPDATE `planes`".
					" SET ".$contenttype."_published=0".
					" WHERE idplan=".$id;
		}
		else {
			$sql = "UPDATE `planes`".
					" SET ".$contenttype."_published=1".
					" WHERE idplan=".$id;		
		}
		
		mysql_query($sql);
	
	}
	
	
	/**
	 * Agrega un nuevo plan
	 */	
	public static function add($nombre, $caracgral, $caracunidad, $proyinversion) {

		require_once ('include/connect.php');
		
		$sql = "INSERT INTO `planes` (`idplan`, `nombre`, `caracgral`, `caracunidad`, `proyinversion`, `imagecount`, `planoscount`, `images_published`, `planos_published`, `published`, `nombre_published`, `caracgral_published`, `caracunidad_published`, `proyinversion_published`)".
				" values (NULL , '". $nombre ."', '". $caracgral."', '". $caracunidad."', '" . $proyinversion . "', '0', '0', '1', '1', '1', '1', '1', '1', '1')";
		$result = mysql_query($sql);
		
		return $result;
	
	}
	
	
	/**
	 * Actualiza un plan
	 */	
	public static function update($id, $nombre, $caracgral, $caracunidad, $proyinversion) {

		require_once ('include/connect.php');
		
		$sql = "UPDATE `planes`".
					" SET nombre='".$nombre."',".
					" caracgral='".$caracgral."',".
					" caracunidad='".$caracunidad."',".
					" proyinversion='".$proyinversion."'".
					" WHERE idplan=".$id;
		$result = mysql_query($sql);

		return $result;
	
	}

	
	/**
	 * Elimina un plan
	 */	
	public static function remove($id) {

		require_once ('include/connect.php');
		
		// TODO Faltan eliminar las imagenes (DB y archivos)

		// Elimina todas las fotos del plan
		$fotos = PlanesDBPlugin::getImages($id, "foto");
		foreach($fotos as $foto) {
		//while($image = mysql_fetch_assoc($results)) {
			PlanesDBPlugin::removeImage($id, $foto[idimage], 'planes', 'imagecount');
		}

		// Elimina todos las planos del plan
		$planos = PlanesDBPlugin::getImages($id, "plano");
		foreach($planos as $plano) {
		//while($image = mysql_fetch_assoc($results)) {
			PlanesDBPlugin::removeImage($id, $plano[idimage], 'planos', 'planoscount');
		}
		
		// Elimina el plan
		$sql = "DELETE FROM `planes`".
					" WHERE idplan=".$id;
		$result = mysql_query($sql);

		return $result;
	
	}
	
	
	/**
	 * Elimina varios planes
	 */	
	public static function removePlanes($idplanes) {
	
		$idplanes = explode(".",$idplanes);
		for($i = 0; $i < count($idplanes); $i++) {
			PlanesDBPlugin::remove($idplanes[$i]);
		}
	}
	
	/*
	 * Agrega una imagen al plan
	 */
	public static function addImage($id, $name, $tmpName, $imagetype, $folder, $count) {

		require_once ('include/connect.php');
		require('conf/configuration.php');

		if (!file_exists($tmpName)) {
			$message = "Error: La imagen no se ha cargado, intente nuevamente";
			return $message;		
		}
		
		// Obtener la cantidad de imagenes
		$plan = PlanesDBPlugin::getById($id);
		$nextImageCount = $plan[$count] + 1;
	
		// Copio la imagen a images/obra
		require_once 'plugin/FileUtilityPlugin.php';
		$extension = FileUtilityPlugin::getExtension($name);
		$newFileName =  'plan' . $id . '_' . $nextImageCount . '.' . $extension;
		while (file_exists($imagesDir[$folder]. $newFileName)) {
			$nextImageCount++;
			$newFileName =  'plan' . $id . '_' . $nextImageCount . '.' . $extension;
		}
		//$path = "../images/obra/" . $newFileName;
		$path = $imagesDir[$folder] . $newFileName;
		copy($tmpName, $path);
		
		// Redimensionar la imagen  
		$thumb = new Thumbnail($imagesDir[$folder] . $newFileName);
 		$thumb->resize($commonImage[width], $commonImage[height]);
		$thumb->save($imagesDir[$folder] . $newFileName, $commonImage[quality]);
		

		// Inserta la imagen en la DB
		$sql = "insert into `images` (`idimage`, `tablename`, `iditem`, `file`, `filetype`, `order`, `imagetype`)".
				" values (NULL, 'planes', " . $id . ", '". $newFileName ."', '".$extension. "', null, '".$imagetype. "')";
		$result = mysql_query($sql);

		// Create thumbnail
		$thumb = new Thumbnail($imagesDir[$folder] . $newFileName);
 		$thumb->resize($thumbnailProp[width], $thumbnailProp[height]);
		$thumb->save($imagesDir[$folder].'small/' . $newFileName, $thumbnailProp[quality]);
		
		
		// Incremento imagecount
		$sql = "update `planes`".
				" set $count = $count + 1".
				" where idplan=".$id;
		$result = mysql_query($sql);	

		$message = "Se ha agregado la imagen correctamente";
		return $message;
	
	}
	
	/**
	 * Obtiene las imagenes de un plan
	 */
	public static function getImages($id, $imagetype) {

		require_once ('include/connect.php');
	
		$sql = "select * from `images`".
		 		" where tablename = 'planes'".
				" and iditem = ".$id.
				" and imagetype = '".$imagetype."'";
		$result = mysql_query($sql);

		$images = array();
		while($image = mysql_fetch_assoc($result)) {
			$images[] = $image;
		}
		
		return $images;
	}
	
	/*
	 * Obtiene una imagen por idimage
	 */
	public static function getImageById($id) {

		require_once ('include/connect.php');
		
		$sql = "select * from `images`".
				" where idimage = ".$id;
		$result = mysql_query($sql);
		$num = mysql_num_rows($result);
		if ($num > 0) {
			$row = mysql_fetch_array($result);
			return $row;
		}
		return null;
	
	}
	
	
	/**
	 * Elimina una imagen del plan
	 */	
	public static function removeImage($idPlan, $idimage, $folder, $count) {

		require_once ('include/connect.php');
		require('conf/configuration.php');
		require_once 'plugin/FileUtilityPlugin.php';
		
		// Elimino el archivo de la imagen
		$image = PlanesDBPlugin::getImageById($idimage);
		FileUtilityPlugin::remove($imagesDir[$folder].$image[file]);
		FileUtilityPlugin::remove($imagesDir[$folder].'small/'.$image[file]);

		// Decremento imagecount
		$sql = "update `planes`".
				" set $count = $count - 1".
				" where idplan=".$idPlan;
		$result = mysql_query($sql);
		
		require_once 'plugin/ImagesDBPlugin.php';
		ImagesDBPlugin::remove($idimage);
		
		return $result;
	
	}

	
	/**
	* Elimina varias imagenes del plan
	*/
	public static function removeImages($idPlan, $idimages, $folder, $count) {
	
		$idimages = explode(".",$idimages);
		for($i = 0; $i < count($idimages); $i++) {
			PlanesDBPlugin::removeImage($idPlan, $idimages[$i], $folder, $count);
		}
	}

	
	/**
	* Guarda la descripcion de una imagen
	*/
	public static function saveImgInfo($idImage, $info) {
	
		require_once ('include/connect.php');
	
		$sql = "UPDATE `images` ";
		$sql .= " SET info ='" . $info . "'";
		$sql .= " WHERE idimage=". $idImage;
		
		mysql_query($sql);
		
	}
	
	
}

?>